package com.ciban.smarthome.module.engine;

import android.content.Context;
import android.view.SurfaceView;

import com.ciban.smarthome.common.utils.DateUtils;
import com.ciban.smarthome.common.utils.FileUtils;
import com.ciban.smarthome.common.utils.StringUtils;
import com.ciban.smarthome.common.utils.logcrash.LogUtil;
import com.ciban.smarthome.module.db.dao.MonitorDao_DH;
import com.ciban.smarthome.module.engine.base.BaseEngine;
import com.ciban.smarthome.module.entity.Equip_Monitor_Dh;
import com.company.NetSDK.CB_fDisConnect;
import com.company.NetSDK.CB_fHaveReConnect;
import com.company.NetSDK.CB_fMessageCallBack;
import com.company.NetSDK.CB_fRealDataCallBackEx;
import com.company.NetSDK.CB_fSubDisConnect;
import com.company.NetSDK.DEV_PLAY_RESULT;
import com.company.NetSDK.INetSDK;
import com.company.NetSDK.NET_DEVICEINFO;
import com.company.NetSDK.NET_PARAM;
import com.company.PlaySDK.Constants;
import com.company.PlaySDK.IPlaySDK;
import com.lidroid.xutils.HttpUtils;

/**
 * 大华摄像头的管理类
 */
public class MonitorDHEngine extends BaseEngine {

    private MonitorDao_DH dao;

    public interface MonitorListener {
        public void monitorLoginResult(boolean result, String errMsg);
    }

    private SurfaceView play_view;

    private long m_loginHandle;
    private long lRealHandle = 0;
    private int nPort;
    private int m_nGlobalChn = 0;
    private int nCurVolume = -1;
    private RealDataCallBack real_callback;
    private MonitorListener listener;


    public MonitorDHEngine(Context context) {
        super(context);
    }

    private void checkDao() {
        if (dao == null)
            dao = new MonitorDao_DH(context);
    }

    /**
     * 添加新的摄像头
     *
     * @param info
     */
    public boolean addNewMonitor(Equip_Monitor_Dh info) {

        String id = addNewEquipMent(info);
        if(!StringUtils.isEmpty(id)){
            checkDao();
            return dao.addNewCamera(info)>0;
        }
        return false;
    }

    /**
     * 初始化摄像头相关配置
     */
    public void initMonitor() {
        INetSDK.LoadLibrarys();

        DeviceDisConnect disConnect = new DeviceDisConnect();
        boolean zRet = INetSDK.Init(disConnect);

        INetSDK.SetConnectTime(4000, 3); // 等待时间 重连次数

        NET_PARAM stNetParam = new NET_PARAM();
        stNetParam.nWaittime = 30000; // 函数等待超时时间
        stNetParam.nSearchRecordTime = 30000; // 录像回放超时时间
        INetSDK.SetNetworkParam(stNetParam);

    }

    /**
     * 摄像头登陆
     */
    public void monitorLogin() {
        Integer error = new Integer(0);

        NET_DEVICEINFO deviceInfo = new NET_DEVICEINFO();

        DeviceReConnect reConnect = new DeviceReConnect();
        INetSDK.SetAutoReconnect(reConnect);

        DeviceSubDisConnect subDisConnect = new DeviceSubDisConnect();
        INetSDK.SetSubconnCallBack(subDisConnect);

        INetSDK.SetDVRMessCallBack(new Pro_CB_fMessageCallBack());

        m_loginHandle = INetSDK.LoginEx("192.168.1.109", 37777, "admin",
                "cibanhome", 20, null, deviceInfo, error);

        boolean result;
        String errMsg;
        if (m_loginHandle != 0) {
            LogUtil.d(MonitorDHEngine.class, "登陆成功：loginhandle=" + m_loginHandle);
            result = true;
            errMsg = null;
        } else {
            LogUtil.d(MonitorDHEngine.class, "登陆失败：错误码=" + error);
            result = false;
            errMsg = "登陆失败：错误码=" + error;
        }
        if (listener != null) {
            listener.monitorLoginResult(result, errMsg);
        }
    }

    public void initSurface() {
        IPlaySDK.InitSurface(nPort, play_view);
    }

    /**
     * 开始实时播放
     *
     * @param nStreamType
     * @return
     */
    public boolean StartRealPlay(int nStreamType) {
        lRealHandle = INetSDK.RealPlayEx(m_loginHandle, m_nGlobalChn,
                nStreamType);

        if (lRealHandle == 0) {
            return false;
        }

        nPort = IPlaySDK.PLAYGetFreePort();

        boolean bOpenRet = IPlaySDK.PLAYOpenStream(nPort, null, 0,
                1024 * 1024 * 2) == 0 ? false : true;

        if (bOpenRet) {
            boolean bPlayRet = IPlaySDK.PLAYPlay(nPort, play_view) == 0 ? false
                    : true;
            if (bPlayRet) {
                boolean bSuccess = IPlaySDK.PLAYPlaySoundShare(nPort) == 0 ? false
                        : true;
                if (!bSuccess) {
                    IPlaySDK.PLAYStop(nPort);
                    IPlaySDK.PLAYCloseStream(nPort);
                    return false;
                }

                if (-1 == nCurVolume) {
                    nCurVolume = IPlaySDK.PLAYGetVolume(nPort);
                } else {
                    IPlaySDK.PLAYSetVolume(nPort, nCurVolume);
                }
            } else {
                IPlaySDK.PLAYCloseStream(nPort);
                return false;
            }
        } else {
            return false;
        }
        return true;
    }

    /**
     * 停止实时播放
     */
    public void StopRealPlay() {
        if (lRealHandle == 0) {
            return;
        }

        try {
            IPlaySDK.PLAYStop(nPort);
            IPlaySDK.PLAYStopSoundShare(nPort);
            IPlaySDK.PLAYCloseStream(nPort);

            INetSDK.StopRealPlayEx(lRealHandle);
        } catch (Exception e) {
            e.printStackTrace();
        }
        lRealHandle = 0;
    }

    /**
     * 添加实时视频的信息回调
     */
    public void addRealCallBack() {
        real_callback = new RealDataCallBack();
        if (lRealHandle != 0) {
            INetSDK.SetRealDataCallBackEx(lRealHandle, real_callback, 1);
        }
    }

    /**
     * 屏幕抓图
     */
    public boolean capture() {
        if (0 != lRealHandle) {
            String path = com.ciban.smarthome.module.Constants.IMG_SAVE_PATH;
            String name = DateUtils.getNow("yyyyMMddHHmmss") + ".bmp";
            if (FileUtils.createFile(path, name)) {
                int nRet = IPlaySDK.PLAYCatchPicEx(nPort, path + name,
                        Constants.PicFormat_BMP);
                if (0 != nRet) {
                    return true;
                }
            }
        }
        return false;
    }

    public void setListener(MonitorListener listener) {
        this.listener = listener;
    }

    public void setPlay_view(SurfaceView play_view) {
        this.play_view = play_view;
    }

    /**
     * 消息回调函数原型
     *
     * @author lenovo
     */
    private class Pro_CB_fMessageCallBack implements CB_fMessageCallBack {
        @Override
        public boolean invoke(int lCommand, long lLoginID, Object obj,
                              String pchDVRIP, int nDVRPort) {
            LogUtil.info("Event: " + lCommand);
            if (12295 == lCommand) {
                DEV_PLAY_RESULT stResult = (DEV_PLAY_RESULT) obj;
                LogUtil.info("ResultCode: " + stResult.dwResultCode
                        + ", PlayHandle: " + stResult.lPlayHandle);
            }
            return true;
        }
    }

    private class DeviceDisConnect implements CB_fDisConnect {
        @Override
        public void invoke(long lLoginID, String pchDVRIP, int nDVRPort) {
            LogUtil.info("Device " + pchDVRIP + " DisConnect!");
            return;
        }
    }

    private class DeviceReConnect implements CB_fHaveReConnect {
        @Override
        public void invoke(long lLoginID, String pchDVRIP, int nDVRPort) {
            LogUtil.info("Device " + pchDVRIP + " ReConnect!");
        }
    }

    private class DeviceSubDisConnect implements CB_fSubDisConnect {
        @Override
        public void invoke(int emInterfaceType, boolean bOnline,
                           long lOperateHandle, long lLoginID) {
            LogUtil.info("Device SubConnect DisConnect");
        }
    }

    private class RealDataCallBack implements CB_fRealDataCallBackEx {
        @Override
        public void invoke(long lRealHandle, int dwDataType, byte[] pBuffer,
                           int dwBufSize, int param) {
            if (0 == dwDataType) {
                IPlaySDK.PLAYInputData(nPort, pBuffer, pBuffer.length);
            }
        }
    }

}
